/*
   Return a RGB colour value given a scalar v in the range [vmin,vmax]
   In this case each colour component ranges from 0 (no contribution) to
   1 (fully saturated), modifications for other ranges is trivial.
   The colour is clipped at the end of the scales if v is outside
   the range [vmin,vmax]
*/

#include <float.h>

typedef struct {
    double r,g,b;
} COLOUR;

COLOUR GetColour(double v,double vmin,double vmax) {
   COLOUR c = {1.0,1.0,1.0}; // white
   double dv;

   if (v < vmin)
      v = vmin;
   if (v > vmax)
      v = vmax;
   dv = vmax - vmin;

   if (v < (vmin + 0.25 * dv)) {
      c.r = 0;
      c.g = 4 * (v - vmin) / dv;
   } else if (v < (vmin + 0.5 * dv)) {
      c.r = 0;
      c.b = 1 + 4 * (vmin + 0.25 * dv - v) / dv;
   } else if (v < (vmin + 0.75 * dv)) {
      c.r = 4 * (v - vmin - 0.5 * dv) / dv;
      c.b = 0;
   } else {
      c.g = 1 + 4 * (vmin + 0.75 * dv - v) / dv;
      c.b = 0;
   }

   return(c);
}

/*
float * maxAndMinFromField(float * field, int size) {
	float maxmin[2];
	float max = -FLT_MAX;
	float min = FLT_MAX;
	for(int i = 0; i < size; i++) {
		if(field[i] > max) {
			max = field[i];
		}
		if(field[i] < min) {
			min = field[i];
		}
	}
	maxmin[0] = max;
	maxmin[1] = min;

	return maxmin;
}

COLOUR * newColourForField(float * field, int size) {
	COLOUR * colourRamp = new COLOUR[size];
	float * maxmin = maxAndMinFromField(field, size);
	for(int i = 0; i < size; i++) {
		colourRamp[i] = GetColour(field[i], maxmin[1], maxmin[0]);
	}
	return colourRamp;
}
*/